package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    StringRedisTemplate redisTemplate;

    public Result queryShopById3(Long id) {

        String shopStr = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(shopStr)) {
            return Result.ok(JSONUtil.toBean(shopStr, Shop.class));
        }
        ;

        if ("".equals(shopStr)) {
            return Result.fail("店铺不存在");
        }
        ;

        Shop shop = getByIdWithMutex(id);

        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        ;
        return Result.ok(shop);

    }

    ;

    static ExecutorService pool = Executors.newFixedThreadPool(10);

    public Result queryShopById(Long id) {

        String redisDataStr = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(redisDataStr)) {
            RedisData redisData = JSONUtil.toBean(redisDataStr, RedisData.class);
            if (redisData.getExpireTime().isBefore(LocalDateTime.now())) {
                cgsy(id);
            }

            return Result.ok(redisData.getData());
        }

        return Result.ok("店铺不存在");
    }

    private void cgsy(Long id) {
        if (getLock(id)) {
            pool.submit(() -> {
                try {
                    Thread.sleep(1000);
                    Shop shop = this.getById(id);
                    if (shop == null) {
                        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_SHOP_TTL, TimeUnit.MINUTES);
                    }

                    RedisData redisData2 = new RedisData();
                    redisData2.setData(shop);
                    redisData2.setExpireTime(LocalDateTime.now().plusSeconds(CACHE_SHOP_TTL));
                    redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData2));
                    releaseLock(id);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    releaseLock(id);
                }
            });
        }
        ;
    }


    Shop getByIdWithLogicalExpiration(Long id) {

        return null;
    }

    Shop getByIdWithMutex(Long id) {
        Shop shop;
        try {
            if (!getLock(id)) {
                Thread.sleep(10000);
                queryShopById(id);
            }
            ;

            shop = this.getById(id);

            if (shop == null) {
                redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_SHOP_TTL, TimeUnit.MINUTES);
                return null;
            }
            ;

            redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.SECONDS);
            releaseLock(id);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            releaseLock(id);
        }
        ;

        return shop;

    }

    ;


    boolean getLock(Long id) {
        return redisTemplate.opsForValue().setIfAbsent(LOCK_SHOP_KEY + id, "1");
    }

    ;


    void releaseLock(Long id) {
        redisTemplate.delete(LOCK_SHOP_KEY + id);
    }

    ;

}
